//
//  SweepViewController.m
//  1243
//
//  Created by ym on 16/4/16.
//  Copyright © 2016年 1243. All rights reserved.
//

#import "SweepViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "ErWeiMaViewController.h"
#import "ReadLoginData.h"
#import "NetWorkTools.h"
@interface SweepViewController ()<AVCaptureMetadataOutputObjectsDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong) AVCaptureSession *session;//输入输出的中间桥梁
@property (nonatomic, strong) AVCaptureDevice *device;//获取摄像设备
@property (nonatomic, strong) AVCaptureDeviceInput *input;//创建输入流
@property (nonatomic, strong) AVCaptureMetadataOutput *output;//创建输出流
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *layer;
@property (nonatomic, strong) UIView *scanRectView;
@end

@implementation SweepViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"扫一扫";
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"upMusic"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
//    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    
    //获取摄像设备
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //创建输入流
    self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    //创建输出流
    self.output = [[AVCaptureMetadataOutput alloc] init];
    //设置代理 在主线程里刷新
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    //初始化链接对象
    self.session = [[AVCaptureSession alloc] init];
    //高质量采集率
    [self.session setSessionPreset:AVCaptureSessionPresetHigh];
    
    [self.session addInput:self.input];
    [self.session addOutput:self.output];
    //设置扫码支持的编码格式
    self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
    
    AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    layer.frame = self.view.layer.bounds;
    [self.view.layer insertSublayer:layer atIndex:0];
    
    //扫描框
    CGSize windowSize = [UIScreen mainScreen].bounds.size;
    CGSize scanSize = CGSizeMake(windowSize.width * 5 / 8, windowSize.width * 5 / 8);
    CGRect scanRect = CGRectMake((windowSize.width - scanSize.width) / 2, (windowSize.height - scanSize.height) / 2 - 100, scanSize.width, scanSize.height);
    scanRect = CGRectMake(scanRect.origin.y / windowSize.height, scanRect.origin.x / windowSize.width, scanRect.size.height / windowSize.height,scanRect.size.width / windowSize.width);
    
    self.output.rectOfInterest = scanRect;
    
    scanRect = CGRectMake((windowSize.width - scanSize.width) / 2, (windowSize.height - scanSize.height) / 2 - 100, scanSize.width, scanSize.height);
    
    self.scanRectView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"xiangkuang"]];
    [self.view addSubview:self.scanRectView];
    self.scanRectView.frame = scanRect;
    self.scanRectView.layer.borderColor = [UIColor orangeColor].CGColor;
    self.scanRectView.layer.borderWidth = 1;
    
    //button上的黑色底纹
    UIGraphicsBeginImageContext(self.view.bounds.size);
    UIBezierPath *path1 = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, scanRect.origin.x+0.1, scanRect.origin.y+scanRect.size.height)];
    UIBezierPath *path2 = [UIBezierPath bezierPathWithRect:CGRectMake(scanRect.origin.x, 0, self.view.bounds.size.width-scanRect.origin.x, scanRect.origin.y+0.1)];
    UIBezierPath *path3 = [UIBezierPath bezierPathWithRect:CGRectMake(-0.1+scanRect.origin.x+scanRect.size.width, scanRect.origin.y, scanRect.origin.x, self.view.bounds.size.height-scanRect.origin.y)];
    UIBezierPath *path4 = [UIBezierPath bezierPathWithRect:CGRectMake(0, -0.1+scanRect.origin.y+scanRect.size.height, scanRect.origin.x+scanRect.size.width, self.view.bounds.size.height-scanRect.size.height-scanRect.origin.y)];
    UIBezierPath *path5 = [UIBezierPath bezierPathWithRect:CGRectMake(0, self.view.bounds.size.height-110, self.view.bounds.size.width, 110)];
    [[UIColor colorWithWhite:0.000 alpha:0.360] setFill];
    [path1 fill];
    [path2 fill];
    [path3 fill];
    [path4 fill];
    [[UIColor colorWithWhite:0.000 alpha:0.710] setFill];
    [path5 fill];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
    [self.view addSubview:imgView];
    
    //
    UILabel *label = [UILabel new];
    label.text = @"将二维码/条码放入框内,即可自动扫描";
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:13];
    label.textColor = [UIColor grayColor];
    scanRect.origin.y = scanRect.origin.y + scanSize.height+5;
    scanRect.size.height = 10;
    [self.view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(@(scanRect.origin.y));
        make.height.equalTo(@20);
    }];
    
    [self downButton];
    
    //开始捕获
    [self.session startRunning];
}
#pragma mark - 下边栏的button们
- (void)downButton
{
    NSMutableArray *DataArr =@[@"我的二维码",@"闪光灯",@"相册"].mutableCopy ;
    NSMutableArray *viewArr = [NSMutableArray array];
    for (int i = 0; i<DataArr.count; i++) {
        
        UIView *view = [[UIView alloc] init];
        [self.view addSubview:view];
        UILabel *label = [[UILabel alloc] init];
        [view addSubview:label];
        label.text = DataArr[i];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor blackColor];
        label.font = [UIFont systemFontOfSize:12];
        UIButton *button = [[UIButton alloc] init];
        [view addSubview:button];
        button.tag = i;
        switch (i) {
            case 0:
                [button addTarget:self action:@selector(pushToInfo) forControlEvents:UIControlEventTouchUpInside];
                [button setImage:[UIImage imageNamed:@"erweima"] forState:UIControlStateNormal];
                break;
            case 1:
                [button setImage:[UIImage imageNamed:@"shanguang"] forState:UIControlStateNormal];
                [button addTarget:self action:@selector(takeFlash) forControlEvents:UIControlEventTouchUpInside];
                break;
            case 2:
                [button addTarget:self action:@selector(pictureAction) forControlEvents:UIControlEventTouchUpInside];
                [button setImage:[UIImage imageNamed:@"wodexiangce"] forState:UIControlStateNormal];
                break;
            default:
                break;
                
        }
        
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(button.mas_height);
            make.centerX.equalTo(view.mas_centerX);
            make.top.equalTo(view).offset(25);
            make.width.height.lessThanOrEqualTo(view);
            make.width.height.equalTo(view).priorityHigh();
        }];
        [button layoutIfNeeded];
        
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(button.mas_height);
            make.top.equalTo(button.mas_bottom).offset(-5);
            make.centerX.equalTo(view.mas_centerX);
        }];
        
        [viewArr addObject:view];
    }
    
    [viewArr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:5 leadSpacing:5 tailSpacing:5];
    [viewArr mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_bottom).offset(-100);
        make.height.equalTo(@60);
    }];
    
}
#pragma mark - 系统相册
- (void)pictureAction
{
    //创建系统自带相册controller
    UIImagePickerController *pickerVC = [[UIImagePickerController alloc] init];
    //签代理,设置代理人
    pickerVC.delegate = self;
    //相册类型
    pickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    //允许编辑
    pickerVC.allowsEditing = YES;
    //跳转到相册
    [self presentViewController:pickerVC animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
    //获取
    UIImage *orgImage = info[UIImagePickerControllerOriginalImage];
    //系统自带识别方法 返回一个二维码扫出来的字符串
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy:CIDetectorAccuracyHigh}];
    CIImage *image = [CIImage imageWithCGImage:orgImage.CGImage];
    NSArray *features = [detector featuresInImage:image];
    CIQRCodeFeature *feature = [features firstObject];
    //name
    NSString *result = feature.messageString;
    NSLog(@"%@", result);
    [picker dismissViewControllerAnimated:YES completion:^{
     //   JCW_AddFriendViewController *addVC = [[JCW_AddFriendViewController alloc] init];
       // addVC.name = result;
        //[self.navigationController pushViewController:addVC animated:YES];
    }];
    
}
#pragma mark - 闪光灯
- (void)takeFlash
{
    //
    [self.device lockForConfiguration:nil];
    //判断是否有闪光灯
    if ([self.device hasFlash]) {
        //如果没有开启则开启 如果开启则关闭
        if (self.device.flashMode == AVCaptureFlashModeOff) {
            [self.device setTorchMode:AVCaptureTorchModeOn];
            self.device.flashMode = AVCaptureTorchModeOn;
        } else {
            [self.device setTorchMode:AVCaptureTorchModeOff];
            self.device.flashMode = AVCaptureTorchModeOff;
        }
    } else {
        NSLog(@"设备不支持闪光灯");
    }
}
#pragma mark - 我的二维码
- (void)pushToInfo
{
    ErWeiMaViewController *a = [[ErWeiMaViewController alloc] init];
    [self.navigationController pushViewController:a animated:YES];
}
#pragma mark - 返回按钮
- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 代理方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count == 0) {
        NSLog(@"%@", metadataObjects);
        return;
    }
    
    if (metadataObjects.count > 0) {
        //停止扫描
        [self.session stopRunning];
        AVMetadataMachineReadableCodeObject *metadataObject = metadataObjects.firstObject;
//        [self.navigationController popViewControllerAnimated:YES];
        NSLog(@"%@", metadataObject.stringValue);
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"转账" message:@"请输入金额和密码" preferredStyle:UIAlertControllerStyleAlert];
        
        //创建文本框
        [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.placeholder = @"请输入金额";
            textField.height = 50;
            textField.returnKeyType = UIReturnKeyGo;
            textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        }];
        //创建文本框
        [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.placeholder = @"请输入交易密码";
            textField.returnKeyType = UIReturnKeyGo;
            textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        }];
        
        NSString *toUserNum = metadataObject.stringValue;
        NSString *fromUserNum = [ReadLoginData readLoginData][@"Number"];
        
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [self.session startRunning];
        }];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSString *turnMoney = alert.textFields[0].text;
            NSString *buy_Password = alert.textFields[1].text;
            NSDictionary *dict = @{
                                   @"ToUserNum":toUserNum,
                                   @"FromUserNum":fromUserNum,
                                   @"TurnMoney":turnMoney,
                                   @"FromPassword":buy_Password,
                                   };
            [[NetWorkTools sharedNetWorkTools] objectWithURLDict:dict AndMenthodName:@"TURNACCOUNT" completeBlock:^(id object) {
                
                NSLog(@"%@", object);
                int message = [object[@"Id"] intValue];
                if (message == 0) {
                    NSLog(@"%@", object[@"Message"]);
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:object[@"Message"] message:nil preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        [self.navigationController popViewControllerAnimated:YES];
                    }];
                    
                    [alert addAction:action];
                    
                    [self presentViewController:alert animated:YES completion:nil];
                } else {
                    NSLog(@"%@", object[@"Message"]);
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:object[@"Message"] message:nil preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        [self.session startRunning];
                    }];
                    
                    [alert addAction:action];
                    [self presentViewController:alert animated:YES completion:nil];
                }
                
            }];
        }];
        
        [alert addAction:action1];
        [alert addAction:action2];
        
        
        [self presentViewController:alert animated:YES completion:nil];
        
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
